
<?php
	///////////////////////////																											
	//const or static variable
	///////////////////////////																											

	define("APP_TYPE_UNKOWN"	, 0);
	define("APP_TYPE_EMAIL"		, 1);
	define("APP_TYPE_GTALK"		, 2);
	define("APP_TYPE_WEIBOQQ"	, 3);
	define("APP_TYPE_WEIBOSINA" , 4);
	define("APP_TYPE_WEIBOTWEET", 5);
	
	///////////////////////////
	//function
	///////////////////////////

	function insert_app_info($account_id, $app_info_array, $app_type = APP_TYPE_UNKOWN, $timestamp, $db = NULL)
	{
		if (empty($app_info_array))
		{
			return;
		}

		foreach ($app_info_array as $k => $app_info)
		{
			$app_account = isset($app_info['Account']) ? $app_info['Account'] : $app_info['WeiboA'];
			$sql_sel = "select * from YBM_bind_account where account_id={$account_id} and ". 
						"account_name='{$app_account}'";
			$rs = $db->query($sql_sel);
	
			$bind_account_id = 0;
			if (empty($rs)) 
			{
				$sql_inst = "insert into YBM_bind_account values(null, {$account_id}, ".
							"{$app_type}, '{$app_account}')";
				$rs = $db->query($sql_inst);
				$rs = $db->query($sql_sel);
	
			}
			$bind_account_id = $rs[0][0];
	
			$sql_inst = sprintf("insert into YBM_BA_statistics values(null, %d, %s, %s, %s, %s, %s)"
								, $bind_account_id
								, $app_info['SendB']
								, $app_info['RecvB']
								, $app_info['Send']
								, $app_info['Send']
								, $timestamp);
			$rs = $db->query($sql_inst);
		}
	}

	//parse the raw data and save to loacl db
	function parse_raw_data($info_json, $db = NULL)
	{
		$report_info_array = json_decode($info_json, true);

		$unique_flag 	= $report_info_array["ID"];
		$email_app 		= $report_info_array["Email"];
		$gtalk_app 		= $report_info_array["IMGtalk"]; 
		$weibo_qq_app 	= $report_info_array["WeiboQQ"]; 
		$weibo_sina_app = $report_info_array["WeiboSina"]; 
		$weibo_tweet_app= $report_info_array["WeiboT"]; 
	
		$timestamp 		= $report_info_array["Time"];
		$geo_info		= $report_info_array["GEO"];

		//find user account
		$sql_sel = "select * from YBM_account where unique_flag = '{$unique_flag}'";
		$rs = $db->query($sql_sel);
		
		$account_id = 0;
		if (empty($rs)) 
		{
			//no user account, then create new
			$sql_inst = "insert into YBM_account values(null, '{$unique_flag}')";	
			$rs = $db->query($sql_inst);

			$rs = $db->query($sql_sel);
		}
		$account_id = $rs[0][0];


		//YBM statistics data
		insert_app_info($account_id, $email_app, APP_TYPE_EMAIL, $timestamp, $db);
		insert_app_info($account_id, $gtalk_app, APP_TYPE_GTALK, $timestamp, $db);
		insert_app_info($account_id, $weibo_qq_app, APP_TYPE_WEIBOQQ, $timestamp, $db);
		insert_app_info($account_id, $weibo_sina_app, APP_TYPE_WEIBOSINA, $timestamp, $db);
		insert_app_info($account_id, $weibo_tweet_app, APP_TYPE_WEIBOTWEET, $timestamp, $db);

		//YBM contact account
		if (empty($email_app))
		{
			$email_app = array();
		}

		foreach ($email_app as $k => $email)
		{
			foreach ($email['AccountS'] as $account)
			{
				$sql_inst = sprintf("insert into YBM_contact_account values(null, '%s', '%s', %d)"
									, $account_id
									, $account
									, APP_TYPE_EMAIL);
				$rs = $db->query($sql_inst);
			}
		}

		//YBM account geo info, x for latitude, y for longitude
		if (empty($geo_info))
		{
			$geo_info = array();
		}

		foreach ($geo_info as $geo)
		{
			$sql_inst = sprintf("insert into YBM_account_geo values(null, %s, %s, %s, %s)"
								, $account_id
								, $geo['t']
								, $geo['x']
								, $geo['y']);
			$rs = $db->query($sql_inst);
		}
	}


	function remote_conncetion_once($last_id)
	{
		//remote db init
		$remote_db = NULL;
		$retry_times = 0;
		$begin_time = 0;
		$end_time = 0;
		$message = "connecting...\n";
		echo $message;

		while (true)
		{
			$begin_time = microtime_float();
			$remote_db = new c_mysql_db(REMOTE_DB_USER, REMOTE_DB_PASS, REMOTE_DB_HOST, REMOTE_DB_NAME);
			if (false == $remote_db->I_linkID)
			{
				$stime = pow(2, $retry_times);
				$stime = $stime  > MAX_SLEEP_TIME ? MAX_SLEEP_TIME : $stime;

				$retry_times++;
				if ($retry_times > MAX_RETRY_TIMES)
				{
					$message = "-1|failed to connect to the remote db, please check the remote server\n";	
					die($message);
					
					//exit the process
				}
				else
				$message = "can't open remote db, {$retry_times} retry after {$stime} second\n";
				echo $message;

				//wait for next connect
				sleep($stime);

				$message = "retrying...\n";
				echo $message;
				continue;
			}
			else
			{
				$end_time = microtime_float();
				$message = "connect to remote db successful. ". round($end_time -
						$begin_time, 2). "s\n";
				echo $message;
				break;
			}
		}

		$sql_sel = sprintf("select * from YBM_raw_data where id > %d order by id asc limit %d"
							, $last_id
							, MAX_READ_COUNT);

		$begin_time = microtime_float();
		$rs = $remote_db->query($sql_sel);
		$end_time = microtime_float();

		$message = "remote select time: " . round($end_time - $begin_time, 2) . "s\n";
		echo $message;

		$remote_db->logoff();

		return $rs;
	}

	///////////////////////////	
	//main process
	///////////////////////////	

	include_once "global.php";
	include_once "../public/util.php";
	include_once "../public/c_mysql_db.inc.php";

	//parse the init xml
	$last_read_id = 0;
	$last_read_time = 0;

	$file_path = './conf/runtime.xml';
	$xml = NULL;
	if (file_exists($file_path))
	{
		$xml = simplexml_load_file($file_path);
		$last_read_id = intval($xml->last_read_id);
		$last_read_time = strval($xml->last_read_time);
	}
	else
	{
		$message = "-1|can't open the config file : {$file_path}";	
		die($message);
	}


	//$report_info_json =	'{"IMGtalk":[{"Send":1,"RecvB":1,"SendB":1,"Recv":1,"Account":"yuchdroid@gmail.com"},{"Send":2,"RecvB":2,"SendB":2,"Recv":2,"Account":"yuchberry@gmail.com"}],"Time":1315906447,"Email":[{"Send":3,"RecvB":3,"SendB":3,"AccountS":[],"Recv":0,"Account":"tzt-123@163.com"},{"Send":0,"RecvB":0,"SendB":0,"AccountS":["lwoxx.fan@gmail.com","lwoxx.bear@gmail.com"],"Recv":0,"Account":"yuchting@gmail.com"},{"Send":0,"RecvB":0,"SendB":0,"AccountS":[],"Recv":0,"Account":"233010045@qq.com"}],"GEO":[{"t":1315906447,"y":0,"x":0},{"t":1315906447,"y":0,"x":0}],"WeiboQQ":[{"Send":0,"RecvB":0,"SendB":0,"Recv":0,"Account":"yuchberry"}],"WeiboT":[],"ID":"null--1","WeiboSina":[{"Send":0,"RecvB":0,"SendB":0,"Recv":0,"Account":2132827701},{"Send":0,"RecvB":0,"SendB":0,"Recv":0,"Account":1894359415}]}';

	//synchronize the raw data
	do 
	{
		$rs = remote_conncetion_once($last_read_id);
		$rs_count = count($rs);

		//local db init
		$local_db = new c_mysql_db(DB_USER, DB_PASS, DB_HOST, DB_NAME);
		if (false == $local_db)
		{
			$message = "can't open local db, {$retry_times} retry after {$stime} second\n";
			die($message);
		}
		

		$begin_time = microtime_float();
		$message = "synchronizing...\n";
		echo $message;

		foreach ($rs as $k => $v)
		{
			$last_read_id = intval($v[0]);
			$sql_inst = sprintf("insert into YBM_raw_data values(null, '%s', '%s', '%s', '%s', '%s', '%s')"
							, $v[1]				//raw_data_unparse
							, $v[2]				//raw_data
							, $v[3]				
							, $v[4]
							, $v[5]
							, $v[0]);

			$local_db->query($sql_inst);

			if (!empty($v[2]))
			{
				parse_raw_data($v[2], $local_db);
			}
		}
		$local_db->logoff();

		$end_time = microtime_float();
		$stime = round($end_time - $begin_time, 2);
		$message = "synchronize the data successful, {$stime}s\n";
		echo $message;
		$xml->last_read_id = $last_read_id;
		$xml->last_read_time = date("Y-m-d H:i:s");
		$newxml = $xml->asXML();
		$fp = fopen($file_path, 'w');
		fwrite($fp, $newxml);
		fclose($fp);

	// read the raw date until the newest id
	} while (!($rs_count < MAX_READ_COUNT || $rs_count == 0));


?>
